﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace THenu.TinyHourseLib
{
    public partial class FrmRichTextBoxFormat : Form
    {
        string formatStringRTF = @"{\colortbl;\red255\green0\blue0;\red0\green255\blue0;\red0\green0\blue255;}";

        public FrmRichTextBoxFormat()
        {
            InitializeComponent();

            //Get RTF from richtextbox

            string strRTF = myRTBEditor.Rtf;
            // Search for colour table info. If it exists (it shouldn't,
            // but we'll check anyway) remove it and replace with our one
            int iCTableStart = strRTF.IndexOf("colortbl;");

            if (iCTableStart != -1) //then colortbl exists
            {
                //find end of colortbl tab by searching
                //forward from the colortbl tab itself
                int iCTableEnd = strRTF.IndexOf('}', iCTableStart);

                //remove the existing colour table
                strRTF = strRTF.Remove(iCTableStart, iCTableEnd - iCTableStart);

                //now insert new colour table at index of old colortbl tag
                strRTF = strRTF.Insert(iCTableStart,
                    // CHANGE THIS STRING TO ALTER COLOUR TABLE
                @"colortbl;\\red255\\green0\\blue0;\\red0\\green128\\blue0;red0\\green0\\blue255;}");
            }

            //colour table doesn't exist yet, so let's make one
            else
            {
                // find index of start of header
                int iRTFLoc = strRTF.IndexOf("\\rtf");
                // get index of where we'll insert the colour table
                // try finding opening bracket of first property of header first                
                int iInsertLoc = strRTF.IndexOf('{', iRTFLoc);

                // if there is no property, we'll insert colour table
                // just before the end bracket of the header
                if (iInsertLoc == -1) iInsertLoc = strRTF.IndexOf('}', iRTFLoc) - 1;

                // insert the colour table at our chosen location                
                strRTF = strRTF.Insert(iInsertLoc,
                    // CHANGE THIS STRING TO ALTER COLOUR TABLE
                    @"{\\colortbl ;\\red128\\green0\\blue0;\\red0\\green128\\blue0;d0\\green0\\blue255;}");
            }

            myRTBEditor.Rtf = strRTF;
        }
    }
}
